package com.zola.blog.gateway.config1;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

/**
 * @author zehua
 * @Date: 2022/4/15 - 01 -02 - 22:36
 * @Description: 限流配置
 * @Version: 1.0
 */
@Configuration
public class RateLimitConfig {

    /**
     * ip限流  1s 100次
     * userId限流 1s 100次
     * 路径限流
     */
    @Bean
    @Primary
    public KeyResolver pathKeyResolver() {
        //写法1
        return exchange -> Mono.just(
                exchange.getRequest()
                        .getPath()
                        .toString()
        );
        //写法2
//        return new KeyResolver(){
//            @Override
//            public Mono<String> resolve(ServerWebExchange exchange){
//                return Mono.just(exchange.getRequest()
//                        .getPath()
//                        .toString());
//            }
//        };
    }

    /**
     * 根据请求IP限流
     *
     * @return
     */
    @Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(
                exchange.getRequest()
                        .getRemoteAddress()
                        .getHostName()
        );
    }

    /**
     * 根据userid限流
     *
     * @return
     */
    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(
                exchange.getRequest()
                        .getQueryParams()
                        .getFirst("userId")
        );
    }
}